package com.csii.branch.activity.server.impl;

import com.csii.activiti.server.abstraction.constant.MessageType;
import com.csii.activiti.server.abstraction.entity.ActReceivedBy;
import com.csii.activiti.server.abstraction.entity.ActSendMessage;
import com.csii.activiti.server.abstraction.service.ActMessageService;
import com.csii.core.api.Result;
import com.csii.core.util.TenantContext;
import com.csii.galaxy.studio.service.GalaxyStudioBaseService;
import com.csii.modules.system.service.ISysBaseAPI;
import com.csii.user.entity.SysUser;
import com.csii.user.service.ISysUserBaseService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ActMessageServiceImpl implements ActMessageService {

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ISysUserBaseService userBaseService;



    @Override
    public void sendMessage(ActSendMessage sendMessage, MessageType messageType) {
        //如果租户为null时，设置默认租户
        boolean isReductionTenant = false;
        if (TenantContext.getTenant() == null){
            TenantContext.setTenant("0");
            isReductionTenant = true;
        }
        Map<String, String> msgMap = Maps.newHashMap();
        msgMap.put("processName",sendMessage.getProcessName());
        //SysUser user = userBaseService.getUserByName(sendMessage.getInitiator());
        //msgMap.put("initiatorName",user.getRealname());
        msgMap.put("processInstanceId",sendMessage.getProcessInstanceId());
        msgMap.put("iconType",sendMessage.getIconType());
        Set<String> usernameSet = sendMessage.getReceivedByList().stream().map(ActReceivedBy::getUsername).collect(Collectors.toSet());
        usernameSet.add(sendMessage.getInitiator());
        Map<String, SysUser> usernameAndUserMap = queryUsernameAndUser(new ArrayList<>(usernameSet));
        msgMap.put("initiatorName",usernameAndUserMap.get(sendMessage.getInitiator()).getRealname());
        switch (messageType){
            case copy:
                Map<String, String> extras = new HashMap<>();
                for (ActReceivedBy actReceivedBy : sendMessage.getReceivedByList()) {
                    msgMap.put("pwcId",actReceivedBy.getBusId());
                    sysBaseAPI.sendSysAnnouncement("admin",actReceivedBy.getUsername(),null,msgMap,"workflow_copy","3");

                }

                break;
            case done:
                msgMap.put("result","通过");
                sysBaseAPI.sendSysAnnouncement("admin",sendMessage.getInitiator(),null,msgMap,"workflow_finish","3");

                break;
            case todo:
                extras = new HashMap<>();
                for (ActReceivedBy actReceivedBy : sendMessage.getReceivedByList()) {
                    msgMap.put("busId",actReceivedBy.getBusId());
                    sysBaseAPI.sendSysAnnouncement("admin",actReceivedBy.getUsername(),null,msgMap,"workflow_todo","3");
                }
                break;
            case reject:
                msgMap.put("result","驳回");
                sysBaseAPI.sendSysAnnouncement("admin",sendMessage.getInitiator(),null,msgMap,"workflow_finish","3");
                break;
            case withdrawn:
                extras = new HashMap<>();
                for (ActReceivedBy actReceivedBy : sendMessage.getReceivedByList()) {
                    msgMap.put("taskId",actReceivedBy.getBusId());
                    sysBaseAPI.sendSysAnnouncement("admin",sendMessage.getInitiator(),null,msgMap,"workflow_withdrawn","3");
                }
                break;
            case urgingSystem:
                Map<String, Object> paramVariables = sendMessage.getParamVariables();
                Date taskCreateTime = (Date) paramVariables.get("taskCreateTime");
                String type = (String) paramVariables.get("type");
                msgMap.put("remindMsg",type.equals("1")?"自动提醒":"手动提醒");
                Date currentDate = sendMessage.getCurrentDate();
                String delayMsg = getDatePoor(currentDate, taskCreateTime);
                msgMap.put("delayMsg",delayMsg);
                extras = new HashMap<>();
                //设置默认租户
                TenantContext.setTenant("0");
                for (ActReceivedBy actReceivedBy : sendMessage.getReceivedByList()) {
                    msgMap.put("taskId",actReceivedBy.getBusId());
                    sysBaseAPI.sendSysAnnouncement("admin",actReceivedBy.getUsername(),null,msgMap,"workflow_urging_system","3");
                }

                break;
        }
        if (isReductionTenant){
            TenantContext.setTenant(null);
        }
    }

    private Map<String, SysUser> queryUsernameAndUser(List<String> usernames) {
        Result<List<SysUser>> listResult = userBaseService.queryUserByUsernames(usernames);
        List<SysUser> users = listResult.getResult();
        Map<String, SysUser> usernameAndUserMap = users.stream().collect(Collectors.toMap(SysUser::getUsername, item -> item, (v1, v2) -> v2));
        return usernameAndUserMap;
    }


    private  String getDatePoor(Date endDate, Date nowDate) {

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        if (day == 0){
            return hour + "小时";
        }
        return day + "天" + hour + "小时";
    }

}
